package com.beta.auth.controller;

import com.alibaba.fastjson.JSON;
import com.beta.auth.common.ResultVo;
import com.beta.auth.config.UserAuthCfgBean;
import com.beta.auth.constants.CacheConstans;
import com.beta.auth.dto.auth.GetUserInfoDto;
import com.beta.cat.service.RedissonService;
import com.beta.platform.rest.auth.LoginAccountDetail;
import com.beta.platform.rest.auth.LoginAccountSecurity;
import com.beta.user.auth.center.api.model.SelfappAuthAcc;
import com.beta.user.auth.center.api.request.QuerySelfAppAuthAccReq;
import com.beta.user.auth.center.api.response.CommonResultEnum;
import com.beta.user.auth.center.api.response.QuerySelfAppAuthAccResp;
import com.beta.user.auth.center.api.service.IRPCSelfAppAuthAccService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * <p>Pro.UserCenter/com.beta.auth.controller.UserController</p>
 *
 * @description 请填写描述信息
 * @author: zdwang
 * @date 2021/12/3 09:09
 */
@Slf4j
@RestController
@RequestMapping("resource")
public class UserResourceController {


    @Autowired
    private UserAuthCfgBean userAuthCfgBean;

    @Autowired
    private RedissonService redissonService;

    @DubboReference
    private IRPCSelfAppAuthAccService authAccService;

    /**
     * 获取用户ID
     *
     * @param code
     * @param token
     * @return
     */
    @RequestMapping("getUserInfo")
    public ResultVo<GetUserInfoDto> getUserInfo(@RequestParam("code") String code, @RequestParam("token") String token) {
        if (StringUtils.isBlank(code)) {
            log.info("SaasAuthController getUserInfo code={}, 参数异常", code);
            return ResultVo.failure(CommonResultEnum.PARAMETER_ERROR);
        }
        String key = String.format(CacheConstans.SAAS_AUTH_USER_INFO, code);
        GetUserInfoDto userInfo = redissonService.get(key, GetUserInfoDto.class);
        log.info("SaasAuthController getUserInfo code={}, userInfo={}", code, JSON.toJSONString(userInfo));
        if (!Objects.isNull(userInfo)) {
            return ResultVo.success(userInfo);
        }
        return ResultVo.success();
    }

    @RequestMapping("getAvatarBase64")
    public ResultVo<String> getAvatarBase64() {
        LoginAccountDetail loginAccountDetail = LoginAccountSecurity.getLoginAccountDetail();
        if (loginAccountDetail == null
                || loginAccountDetail.getThirdUserInfo() == null) {
            log.warn("请求头缺少用户信息");
            return ResultVo.failure(CommonResultEnum.MISSING_REQUEST_PARAMETER);
        }

        String userId = loginAccountDetail.getThirdUserInfo().getUserId();
        if (StringUtils.isEmpty(userId)) {
            log.warn("getAvatarBase64获取用户ID为空");
            return ResultVo.failure(CommonResultEnum.MISSING_REQUEST_PARAMETER);
        }

        QuerySelfAppAuthAccResp queryResp = authAccService.querySelfAppAuthAcc(new QuerySelfAppAuthAccReq().setAppId(userAuthCfgBean.getCorpId()).setUserId(userId));
        if (queryResp== null || !queryResp.isSucc()) {
            log.error("查询用户（userId={}）信息失败，返回：{}", userId, JSON.toJSONString(queryResp));
            return ResultVo.failure(CommonResultEnum.SYSTEM_HAS_MALFUNCTIONED);
        }

        SelfappAuthAcc selfAppAuthAcc = queryResp.getSelfAppAuthAcc();
        if (selfAppAuthAcc == null) {
            log.error("未查询用户（userId={}）信息，返回：{}", userId, JSON.toJSONString(queryResp));
            return ResultVo.failure(CommonResultEnum.EMPTY_RESULT);
        }

        return ResultVo.success(selfAppAuthAcc.getAvatarBase64());
    }
}
